import { setToken, removeToken } from '@/utils/token'
import _this from '@/main.js'

const user = {
  state: {
    user: null
  },

  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    }
  },

  actions: {
    // 登录
    LOGIN ({ commit }, loginForm) {
      return new Promise((resolve, reject) => {
        _this.$axios.post('/auth/login', loginForm).then(res => {
          setToken(res.data)
          commit('SET_USER', res.data.user)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 退出
    LOGOUT ({ commit }) {
      return new Promise((resolve, reject) => {
        _this.$axios.post('/auth/logout').then(res => {
          commit('SET_USER', null)
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
